package by.vdl.websort.server.dao.hibernate;

import by.vdl.websort.server.dao.BaseDao;
import by.vdl.websort.server.dao.UserDao;
import by.vdl.websort.server.entity.UserDTO;
import by.vdl.websort.server.entity.UserPassedStudyDTO;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * User: zeor
 * Date: 16.11.13
 * Time: 0:16
 */
public class UserDaoImpl extends BaseDao implements UserDao {

    @Transactional
    public List<UserDTO> getUsersList() {
        return sessionFactory.getCurrentSession().createCriteria(UserDTO.class).list();
    }

    @Transactional
    public void create(UserDTO userDTO) {
        sessionFactory.getCurrentSession().save(userDTO);
    }

    @Transactional
    public boolean check(String login, String password) {
        UserDTO user = (UserDTO)sessionFactory.getCurrentSession().createCriteria(UserDTO.class)
                .add(Restrictions.and(Restrictions.eq("name", login),Restrictions.eq("password", password)))
                .uniqueResult();
       if(user != null)
           return true;

        return false;
    }

    @Transactional
    public UserDTO checkUser(String login, String password) {
        return (UserDTO)sessionFactory.getCurrentSession().createCriteria(UserDTO.class)
                .add(Restrictions.and(Restrictions.eq("name", login),Restrictions.eq("password", password)))
                .uniqueResult();
    }

    @Transactional
    public UserPassedStudyDTO addUserPassedStudy(String ip, long studyId) {
        String userIdentity = String.valueOf(System.currentTimeMillis());
        UserPassedStudyDTO userPassedStudyDTO = new UserPassedStudyDTO();
        userPassedStudyDTO.setStudyId(studyId);
        userPassedStudyDTO.setIp(ip);
        userPassedStudyDTO.setUserIdentify(userIdentity);

        sessionFactory.getCurrentSession().save(userPassedStudyDTO);

        return userPassedStudyDTO;
    }

    @Transactional
    public UserDTO getUserById(long userId) throws Exception {
        return (UserDTO)sessionFactory.getCurrentSession().get(UserDTO.class, userId);
    }
}
